<template>
    <div class="detail-page">
        <!-- 导航栏 -->
        <NavBar navbarTitle="商品详情"></NavBar>
        <div class="detail-content">
            <!-- 展示商品图片轮播部分 -->
            <Swipe class="productImg-swiper">
                <swipe-item class="item" v-for="imgUrl,index in productInfo.productImgList" :key="index">
                    <img class="item-img" :src="imgUrl" title="商品图片">
                </swipe-item>
                <template #indicator="{ active, total }">
                    <div class="custom-indicator">{{ active + 1 }}/{{ total }}</div>
                </template>
            </Swipe>
            <!-- 商品价格及销量展示 -->
            <div class="product-price">
                <div class="price-top">
                    <span class="top-tip">￥{{ productInfo.productPrice.toFixed(2) }}起</span>
                    <span class="top-sales">已售{{ productInfo.productSales }}件</span>
                </div>
                <div class="price-bottom">
                    <div class="bottom-preferential">
                        <span class="preferential-item">店铺新客立减2元</span>
                        <span class="preferential-item">两件9折</span>
                    </div>
                    <icon size="15" class="bottom-icon" name="arrow" />
                </div>
            </div>
            <!-- 商品信息展示部分 -->
            <div class="product-info">
                <span class="info-title">{{ productInfo.productName }}</span>
                <span class="info-desc">{{ productInfo.productDescription }}</span>
            </div>
            <!-- 选择商品规格、收货地址、服务部分 -->
            <div class="product-select">
                <div class="select-item select-attr">
                    <span class="item-tip">选择</span>
                    <span class="item-content" @click="selectProductAttr">{{ userSelectInfo.productAttrStr === '' ? '请选择商品规格' : userSelectInfo.productAttrStr}}</span>
                    <Icon class="item-icon" name="arrow" size="13" color="#9195a3" @click="selectProductAttr" />
                </div>
                <div class="select-item select-attr">
                    <span class="item-tip">送至</span>
                    <span class="item-content" @click="selectAddress">{{ userSelectInfo.userAddressStr === '' ? '请选择收货地址' : userSelectInfo.userAddressStr }}</span>
                    <Icon class="item-icon" name="arrow" size="13" color="#9195a3" @click="selectAddress" />
                </div>
                <div class="select-item select-attr">
                    <span class="item-tip">服务</span>
                    <span class="item-content" @click="selectService">七天无理由 快速退款 免费包邮</span>
                    <Icon class="item-icon" name="arrow" size="13" color="#9195a3" @click="selectService"/>
                </div>
            </div>
            <!-- 商品详情部分 -->
            <!-- 商品规格、收货地址、服务选择部分 使用vant弹出层组件 -->
            <van-popup v-model:show="popupIsShow" position="bottom" closeable close-icon="close" class="product-popup">
                <!-- 商品规格信息 -->
                <div class="popup-product" v-if="popupState === 1">
                    <div class="product-info">
                        <img class="info-left" :src="productInfo.productImgList[0]" alt="">
                        <div class="info-right">
                            <span class="right-price">￥{{ userSelectInfo.productPrice > 0 ? userSelectInfo.productPrice.toFixed(2) : productInfo.productPrice.toFixed(2) }}</span>
                            <span class="right-store">库存:{{ userSelectInfo.productStore }}</span>
                            <span class="right-select">已选:{{ userSelectInfo.productAttrStr === '' ? '未选择商品规格' : userSelectInfo.productAttrStr }}</span>
                        </div>
                    </div>
                    <div class="product-attr">
                        <span class="attr-title">请选择商品规格</span>
                        <div class="attr-items">
                            <span class="items-item" :class="attr.select ? 'active' : '' " v-for="attr,index in productInfo.productAttrList" :key="index" @click="changeAttr(attr)">{{ attr.commodityAttr }}</span>
                        </div>
                    </div>
                    <div class="product-number">
                        <span class="number-left">数量</span>
                        <div class="number-right">
                            <Icon class="right-minus" size="12" name="minus" @click="userSelectInfo.productNum > 1 ? userSelectInfo.productNum -- : '' " />
                            <input class="right-num" type="text" v-model="userSelectInfo.productNum">
                            <Icon class="right-plus" size="12" name="plus" @click="userSelectInfo.productNum ++" />
                        </div>
                    </div>
                    <div class="product-btns">
                        <div class="btns-item-add">加入购物车</div>
                        <div class="btns-item-buy">立即购买</div>
                    </div>
                </div>
                <!-- 收货地址信息 -->
                <div class="popup-address" v-if="popupState === 2">
                    <div class="address-title">
                        <span class="title-tip">配送至</span>
                    </div>
                    <div class="address-content"> 
                        <div class="content-item" v-for="item,index in userAddressList" :key="index">
                            <Icon name="location-o" color="#9195a3" size="20"/>
                            <div class="item-userInfo">
                                <div class="userInfo-top">
                                    <span class="top-username">{{ item.linkUser }}</span>
                                    <span class="top-userphone">{{ item.linkPhone }}</span>
                                </div>
                                <div class="userInfo-bottom">
                                    <span class="bottom-address">{{ item.linkAddress }}</span>
                                </div>
                            </div>
                            <Checkbox v-model="item.isSelected" @click="userAddressChange(item.id)"></Checkbox>
                        </div>
                    </div>
                    <div class="address-btn">
                        <van-button class="btn-button" icon="plus" size="small" type="success" @click="addUserAddress_btn">添加收货地址</van-button>
                    </div>
                </div>
                <!-- 商品服务信息 -->
                <div class="popup-service" v-if="popupState === 3">
                    <div class="service-title">
                        <span class="title-tip">星辰集市服务说明</span>
                    </div>
                    <div class="service-content">
                        <div class="content-item">
                            <span class="item-title">无忧退货</span>
                            <span class="item-content">自收到货之日30天内,可在线申请无忧退货服务(损耗品等特殊商品除外)</span>
                        </div>
                        <div class="content-item">
                            <span class="item-title">快速退款</span>
                            <span class="item-content">收到退货包裹并确认无误后,将在48小时内办理退款,退款将原路返回,不同银行处理时间不同,预计1-5个工作日到账</span>
                        </div>
                        <div class="content-item">
                            <span class="item-title">满66元免邮费</span>
                            <span class="item-content">单笔订单金额(不含邮费)满66元免邮费,未满66元,将根据订单配送地址收取配送费</span>
                        </div>
                    </div>
                </div>
            </van-popup>
            <!-- 底部固定功能区：立即购买、加入购物车、购物车 -->
            <div class="product-functionalArea">
                <div class="area-icons">
                    <div class="icons-icon">
                        <Icon class="icon-item-icon" name="goods-collect-o" size="18" />
                        <span class="icon-item-tip">收藏</span>
                    </div>
                    <div class="icons-icon">
                        <Icon class="icon-item-icon" name="service-o" size="18" />
                        <span class="icon-item-tip">客服</span>
                    </div>
                    <div class="icons-icon">
                        <Icon class="icon-item-icon" name="shopping-cart-o" size="18" />
                        <span class="icon-item-tip">购物车</span>
                    </div>
                </div>
                <div class="area-btns">
                    <van-button class="btns-item" type="primary" size="small" @click="addCart_btn">加入购物车</van-button>
                    <van-button class="btns-item" type="success" size="small" @click="buyNow_btn">立即购买</van-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
//引入vue3组合式函数
import { ref, reactive, onMounted } from "vue";
//引入组件
import NavBar from "@/components/NavBar/NavBar.vue";
//引入vant4组件
import { Swipe, SwipeItem, Popup as VanPopup, Icon, Checkbox, Button as VanButton, showToast, showSuccessToast, showFailToast } from "vant";
//引入请求函数
import { reqProductInfoById } from "@/api/product/index";
import { reqUserAddressList } from "@/api/user/index";
//引入vue-router
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
//引入userStore仓库
import { useUserStore } from "@/store/userStore";
const userStore = useUserStore();
//@ts-ignore引入请求函数
import { reqAddUserCart } from "@/api/cart/index.ts";
//引入mitt全局事件通信插件
import mitt from "@/utils/eventBus";

//控制vant弹出层开闭
let popupIsShow = ref(false);
let popupState = ref(0);  //popup弹出层显示内容状态

//当前id下的商品信息
const productInfo = reactive({
    productId:0,  //商品id
    productName:"",  //商品名称
    productImgList:[],  //商品图片地址数组集合
    productDescription:"",  //商品描述
    productClassificationName:"",  //商品分类名称
    productDiscount:0,  //商品折扣
    productSales:0,  //商品销量
    productSaleMoney:0,  //商品销售额
    productAttrList:[],  //商品规格信息
    productPrice:0  //商品价格 xx起
})
//用户选择的一些信息包含:当前商品规格、规格价格、库存、商品数量、收货信息
const userSelectInfo = reactive({
    productId:0,
    productAttrId:0,
    productAttrStr:"",
    productPrice:0,
    productStore:0,
    productNum:1,
    userAddressId:0,  //用户收货地址id
    userAddressStr:"",  //用户收货地址描述
})
//当前用户下的地址信息
const userAddressList = ref([]);

//请求对应id下的商品信息
const getProductInfoById = async () => {
    const productId = route.query.goodsId;
    if(productId === "" || productId === undefined) return;
    //发请求
    let res = await reqProductInfoById(productId as any);
    //赋值
    productInfo.productId = res.result.productId;
    productInfo.productName = res.result.productName;
    productInfo.productImgList = res.result.productImgs.split(",");
    productInfo.productDescription = res.result.productDescription;
    productInfo.productClassificationName = res.result.productClassificationName;
    productInfo.productDiscount = res.result.productDiscount;
    productInfo.productSales = res.result.productSales;
    productInfo.productSaleMoney = res.result.productSaleMoney;
    productInfo.productAttrList = res.result.commercialSpecificationList;
    productInfo.productPrice = res.result.commercialSpecificationList[0].commodityPrice;
    res.result.commercialSpecificationList.forEach(item => {
        if(productInfo.productPrice > item.commodityPrice){
            productInfo.productPrice = item.commodityPrice;
        }
    });
    console.log("根据商品id获取商品信息api",res);
}
//请求当前用户的收货地址信息
async function getUserAddressList () {
    //判断当前内存中是否已有了收货地址信息
    if(userAddressList.value.length > 0) return;
    //获取当前的用户id信息 仓库获取?  本地存储获取?
    let userId = userStore.userInfo.id || JSON.parse(localStorage.getItem("userInfo")).id;
    let res = await reqUserAddressList(userId);
    if(res.code === 200){
        //给地址每一项加上isSelected属性
        res.result.forEach(item => {
            item.isSelected = false;
            if(item.defaultAddress){
                item.isSelected = true;
                //收集默认的地址信息
                userSelectInfo.userAddressId = item.id;
                userSelectInfo.userAddressStr = item.linkAddress;
            }
        });
        userAddressList.value = res.result;
        showToast("用户地址获取成功!");
    }
    console.log("获取平台会员地址api",res);
}

//点击选择商品规格、收货地址、服务
function selectProductAttr () {
    //打开popup并设置状态
    popupIsShow.value = true;
    popupState.value = 1;
}
function selectAddress () {
    /*判断用户是否登录,未登录跳转到登录页。用户仓库、本地存储是否有用户名数据?*/
    if(!(userStore.userInfo.username || localStorage.getItem("userInfo") !== null)){
        showToast("未登录,即将跳转到登录页...");
        setTimeout(()=>{
            router.push({path:"/login",query:{redirect:route.path + '?goodsId=' + route.query.goodsId}});
        },800)
        return;
    }
    //打开popup并设置状态
    popupIsShow.value = true;
    popupState.value = 2;
    //获取用户的收货地址信息
    getUserAddressList();
}
function selectService () {
    //打开popup并设置状态
    popupIsShow.value = true;
    popupState.value = 3;
}
//商品规格的change
const changeAttr = (productAttr:any) => {
    productInfo.productAttrList.forEach(item => item.select = false);
    productAttr.select = true;
    //展示选择的规格价格、规格、库存信息
    userSelectInfo.productPrice = productAttr.commodityPrice;
    userSelectInfo.productStore = productAttr.commodityStore;
    userSelectInfo.productAttrId = productAttr.id;
    userSelectInfo.productAttrStr = productAttr.commodityAttr;
}
//用户地址的change
const userAddressChange = (userAddressId:number) => {
    userAddressList.value.forEach(item => {
        item.isSelected = false;
        if(item.id == userAddressId) {
            item.isSelected = !item.isSelected;
        }
    });
    //获取、收集选中的值
    userAddressList.value.forEach(item => {
        if(item.id === userAddressId && item.isSelected){
            userSelectInfo.userAddressId = item.id;
            userSelectInfo.userAddressStr = item.linkAddress;
        }
    })
}

//添加用户收货地址按钮
const addUserAddress_btn = () => {
    router.push("/address");
}

//加入购物车按钮
const addCart_btn = async () => {
    /*判断用户是否登录,未登录跳转到登录页。用户仓库、本地存储是否有用户名数据?*/
    if(!(userStore.userInfo.username || localStorage.getItem("userInfo") !== null)){
        showToast("未登录,即将跳转到登录页...");
        setTimeout(()=>{
            router.push({path:"/login",query:{redirect:route.path + '?goodsId=' + route.query.goodsId}});
        },800)
        return;
    }

    //参数准备
    const params = {cartUserId:0,cartCommodityId:0,cartCommodityCount:0,cartCommodityAttr:"",cartCommodityStandardId:0};
    params.cartUserId = userStore.userInfo.id || JSON.parse(localStorage.getItem("userInfo")).id;
    params.cartCommodityId = route.query.goodsId as any;
    params.cartCommodityCount = userSelectInfo.productNum;
    params.cartCommodityAttr = userSelectInfo.productAttrStr;
    params.cartCommodityStandardId = userSelectInfo.productAttrId;
    //参数检查
    if(!params.cartUserId) return showToast("登录过期,请重新登录!");
    if(params.cartCommodityAttr === "") return showToast("请选择商品规格!");
    //发请求加入购物车
    let res = await reqAddUserCart(params);
    if(res.code === 200){
        showSuccessToast("加购成功!在购物车等亲~");
    } else {
        showFailToast("加入购物车失败!");
    }
    console.log("添加用户购物车api",res);
}
//立即购买按钮
const buyNow_btn = () => {
    /*判断用户是否登录,未登录跳转到登录页。用户仓库、本地存储是否有用户名数据?*/
    if(!(userStore.userInfo.username || localStorage.getItem("userInfo") !== null)){
        showToast("未登录,即将跳转到登录页...");
        setTimeout(()=>{
            router.push({path:"/login",query:{redirect:route.path + '?goodsId=' + route.query.goodsId}});
        },800)
        return;
    }

    //用户是否选择了商品规格、收货地址信息
    if(userSelectInfo.productAttrId === 0) return showToast("请选择商品规格!");
    if(userSelectInfo.userAddressStr === "") return showToast("请选择收货地址信息!");
    router.push("/create");
    //传递信息数据(createDetail组件还未挂载,全局事件总线触发不了"orderInfo",延迟发送数据)
    //准备发送的数据
    let address = userAddressList.value.filter(item => item.id === userSelectInfo.userAddressId)[0];
    let product = {commodityId:productInfo.productId,commodityStandardId:userSelectInfo.productAttrId,commodityStandardStr:userSelectInfo.productAttrStr,commodityCount:userSelectInfo.productNum,productName:productInfo.productName,productImg:productInfo.productImgList,productPrice:userSelectInfo.productPrice};
    setTimeout(()=>{
        mitt.emit('orderInfo',{addressInfo:address,productInfo:[product]});
    },200)
}

//vue生命周期
onMounted(() => {
    //获取商品信息
    getProductInfoById();
})
</script>

<style lang="less" scoped>
.detail-content{
    width: 375px;
    height: calc(100vh - 50px - 50px);
    position: relative;
    top:47px;
    overflow: auto;

    /**商品轮播图部分 */
    .productImg-swiper{
        width: 375px;
        height: 350px;
        .item{
            color: #fff;
            font-size: 20px;
            line-height: 350px;
            text-align: center;
            .item-img{
                width: 375px;
                height: 350px;
            }
        }
        .custom-indicator {
            position: absolute;
            right: 5px;
            bottom: 5px;
            padding: 2px 5px;
            font-size: 12px;
            color: #fff;
            background: rgba(0, 0, 0, 0.1);
        }
    }
    /**商品价格及销量展示 */
    .product-price{
        width: 375px;
        height: 60px;
        padding: 5px 10px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        background-color: #efefef;
        .price-top{
            flex: 2;
            display: flex;
            justify-content: space-between;
            align-items: center;
            .top-tip{
                color: #f00;
                font-size: 23px;
            }
            .top-sales{
                font-size: 12px;
            }
        }
        .price-bottom{
            flex:1;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .bottom-preferential{
                font-size: 10px;
                display: flex;
                .preferential-item{
                    margin: 0 5px;
                    padding: 2px 4px;
                    border:0.3px solid #9195a3;
                    color: #9195a3;
                }
            }
            .bottom-icon{
                color: #9195a3;
            }
        }
    }
    /**商品信息展示部分*/
    .product-info{
        width: 375px;
        padding: 5px 10px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        border-bottom: 1px solid #e3e6e4;
        .info-title{
            margin: 7px 0;
            font-size: 16px;
        }
        .info-desc{
            width: 750rpx;
            font-size: 12px;
            color: #9195a3;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    } 
    /**选择商品规格、收货地址、服务部分 */
    .product-select{
        width: 100%;
        padding: 0 20px;
        box-sizing: border-box;
        .select-item{
            width: 100%;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid #e6faed;
            .item-tip{
                font-size: 12px;
                margin-right: 10px;
                color: #9195a3;
            }
            .item-content{
                width: 280px;
                font-size: 12px;
            }
        }
        :last-child{
            border-bottom: none;
        }
    }
    /**商品规格、收货地址、服务部分vant弹出层 */
    .product-popup{
        padding: 15px;
        /**商品信息 */
        .popup-product{
            width: 100%;
            .product-info{
                width: 100%;
                height: 110px;
                display: flex;
                flex-direction: row;
                justify-content: flex-start;
                .info-left{
                    width: 70px;
                    height: 90px;
                    margin-right: 10px;
                }
                .info-right{
                    height: 90px;
                    display: flex;
                    flex-direction: column;
                    justify-content: space-around;
                    .right-price{
                        font-size: 25px;
                        color: #f00;
                    }
                    .right-store{
                        font-size: 12px;
                        color: #9195a3;
                    }
                    .right-select{
                        font-size: 12px;
                        color: #000;
                    }
                }
            }
            .product-attr{
                width: 100%;
                margin: 15px 0;
                .attr-title{
                    font-size: 15px;
                    color: #9195a3;
                }
                .attr-items{
                    font-size: 14px;
                    display: flex;
                    flex-wrap: wrap;
                    margin: 9px 10px;
                    color: #9195a3;
                    .items-item{
                        display: inline;
                        margin: 3px 5px;
                        padding: 7px 9px;
                        background:rgba(#c0e1ff, 0.3);
                        color: #000;
                        border-radius: 5px;
                        cursor: pointer;
                    }
                    .active{
                        background: #f00;
                        color: #fff;
                    }
                }
            }
            .product-number{
                width: 100%;
                display: flex;
                justify-content: space-between;
                align-items: center;
                .number-left{
                    color: #000;
                    font-size: 16px;
                    font-weight: 650;
                }
                .number-right{
                    padding: 2px 6px;
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    font-size: 12px;
                    background: #eff8ff;
                    color: #9195a3;
                    border: 5px;
                    .right-num{
                        width: 35px;
                        height: 23px;
                        text-align: center;
                        border: none;
                        background: #eff8ff;
                    }
                    .right-minus{
                        cursor: pointer;
                    }
                    .right-plus{
                        cursor: pointer;
                    }
                }
            }
            .product-btns{
                margin: 30px 0;
                width: 100%;
                height: 40px;
                display: flex;
                justify-content: space-around;
                align-items: center;
                color: #fff;
                font-size: 16px;
                .btns-item-add{
                    width: 50%;
                    height: 40px;
                    text-align: center;
                    line-height: 40px;
                    background: #07c160;
                    border-bottom-left-radius: 20px;
                    border-top-left-radius: 20px;
                    cursor: pointer;
                    transition: background-color 0.5;
                }
                .btns-item-add:active{
                    background-color: #4fe497;
                }
                .btns-item-buy{
                    width: 50%;
                    height: 40px;
                    text-align: center;
                    line-height: 40px;
                    background: #ee0a24;
                    border-bottom-right-radius: 20px;
                    border-top-right-radius: 20px;
                    cursor: pointer;
                    transition: background-color 0.5;
                }
                .btns-item-buy:active{
                    background-color: #f05366;
                }
            }
        }
        /**收货地址信息 */
        .popup-address{
            width: 100%;
            .address-title{
                width: 100%;
                height: 50px;
                font-size: 16px;
                line-height: 50px;
                text-align: center;
                border-bottom: 1px solid #9fbaac;
            }
            .address-content{
                width: 100%;
                margin: 5px 0;
                .content-item{
                    width: 100%;
                    height: 50px;
                    margin: 10px 0;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    .item-userInfo{
                        width: 290px;
                        height: 40px;
                        font-size: 14px;
                        display: flex;
                        flex-direction: column;
                        justify-content: space-around;
                        .userInfo-top{
                            color: #9195a3;
                        }
                        .userInfo-bottom{
                            color: #9195a3;
                        }
                    }
                }
            }
            .address-btn{
                margin: 20px 0;
                .btn-button{
                    width: 345px;
                }
            }
        }
        /**服务说明部分 */
        .popup-service{
            width: 100%;
            .service-title{
                width: 100%;
                height: 50px;
                font-size: 16px;
                line-height: 50px;
                text-align: center;
                border-bottom: 1px solid #9fbaac;
            }
            .service-content{
                width: 100%;
                margin: 5px 0;
                .content-item{
                    width: 100%;
                    margin: 10px 0;
                    display: flex;
                    flex-direction: column;
                    .item-title{
                        font-size: 13px;
                        font-weight: 550;
                        margin: 5px 0;
                        color: #9195a3;
                    }
                    .item-content{
                        font-size: 12px;
                        color: #b2b3b8;
                    }
                }
            }
        }
    }
    /**底部固定功能区 */
    .product-functionalArea{
        width: 100%;
        height: 50px;
        padding: 0 10px;
        box-sizing: border-box;
        position: fixed;
        bottom: 0;
        z-index: 9;
        display: flex;
        align-items: center;
        border-top: 1px solid #e3e6e4;
        .area-icons{
            width: 100%;
            display: flex;
            .icons-icon{
                margin: 0 10px;
                font-size: 10px;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;
                .icon-item-tip{
                    margin: 2px 0;
                }
            }
        }
        .area-btns{
            display: flex;
            .btns-item{
                width: 90px;
                margin: 0 5px;
            }
        }
    }
}
</style>